<?php

namespace app\admin\controller;

use app\common\model\AnswerMethod;
use app\common\model\QuestionOption;
use think\console\command\Lists;
use think\Lang;
use app\common\model\Goodsclass;
use think\Request;
use think\Session;

/**
 * 设备库管理
 * User: CCA
 * Date: 2019/9/25
 * Time: 16:53
 */
class Nquipment extends AdminControl
{
    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/question.lang.php');
    }

    //首页
    public function index()
    {
        $equipmentModel = new \app\common\model\Equipment();
        $title = input('get.title', '');
        $search_status = input('get.search_status', '');
        $search_gc_id1 = input('get.search_gc_id1', '');
        $search_gc_id2 = input('get.search_gc_id2', '');
        $search_gc_id3 = input('get.search_gc_id3', '');
        $condition = [];
        if ($title) {
            $condition['goods_name'] = array('like', "%" . $title . "%");
        }
        if ($search_status) {
            $condition['status'] = ['eq', $search_status];
        }
        if ($search_gc_id1) {
            $condition['gc_one_id'] = ['eq', $search_gc_id1];
        }
        if ($search_gc_id2) {
            $condition['gc_two_id'] = ['eq', $search_gc_id2];
        }
        if ($search_gc_id3) {
            $condition['gc_three_id'] = ['eq', $search_gc_id3];
        }
        $condition['equipment_del'] = 0;
        $condition['is_store'] = 0;
        // $condition['status'] = 1;  //状态1启用 2禁用
        $condition['equipment_status'] = 1;
       // p($condition);die;
        $equipment_list = $equipmentModel->getNquipmentList($condition, 10);

        $class = new Goodsclass();
        $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
        $this->assign('class_list', $parent_class_list);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件

        $this->assign('title', $title);
        $this->assign('search_gc_id1', $search_gc_id1);
        $this->assign('search_gc_id2', $search_gc_id2);
        $this->assign('search_gc_id3', $search_gc_id3);
        $this->assign('search_status', $search_status);

        $this->assign('equipment_list', $equipment_list);
        $this->assign('show_page', $equipmentModel->page_info->render());
        $this->assign('questionModel', $equipmentModel);

        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /**
     * 舔砖记录
     */
    public function bicks_list()
    {
        $equipmentModel = new \app\common\model\Equipment();
        $file_http = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $file_http['value']);
        /**
         * 查询条件
         */
        $where = array();
        #设备名称
        $search_goods_name = trim(input('param.search_goods_name'));
        if ($search_goods_name != '') {
            $where['goods_name'] = array('like', '%' . $search_goods_name . '%');
        }
        
        //审核状态

        $search_goods_status = trim(input('param.search_goods_status'));
        if ($search_goods_status != '') {
            $where['equipment_status'] = array('eq',  $search_goods_status );
        }else{
            $where['equipment_status'] = array('neq','0');
        }

        #提交人
        $submission_name = trim(input('param.submission_name'));
        if ($submission_name != '') {
            $where['name'] = array('like', '%' . $submission_name . '%');
        }

        $b_id = intval(input('param.b_id'));
        if ($b_id > 0) {
            $where['b_id'] = $b_id;
        }

        $addbricks_model = model('addbricks');

        $where['equipment_del'] = 0;
        $where['is_store'] = 1;
       
        //时间
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $where['ne.created_at'] = array('between', array($query_start_time, $query_end_time));
        }
        //判断是那种类型

        $bricks_list = $equipmentModel->getEquipmentList($where, 10);

        // var_dump($bricks_list);exit;
        $this->assign('bricks_list', $bricks_list);
        $this->assign('show_page', $equipmentModel->page_info->render());

        $this->assign('search_goods_name', $search_goods_name);
        $this->assign('submission_name', $submission_name);
        $this->assign('b_id', $b_id);

        // $storage_array = $goods_model->calculateStorage($goods_list);
        // $this->assign('storage_array', $storage_array);

        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());
        $this->assign('search', $where);
        $this->assign('brand_list', $brand_list);

        $this->assign('enterprise_status', array('0' => '待审核', '1' => '审核通过', '2' => '审核失败'));

        $this->assign('ownShopIds', array_fill_keys(model('store')->getOwnShopIds(), true));

        $type = input('param.type');
        if (!in_array($type, array('lockup', 'waitverify', 'allgoods'))) {
            $type = 'allgoods';
        }

        $this->assign('type', $type);
        $this->assign('is_examine', false);
        $this->setAdminCurItem('two_goods_no');
        return $this->fetch('bicks_list');
    }

    /**
     * 待审核 我要舔砖
     */
    public function two_goods_wait()
    {
        $equipmentModel = new \app\common\model\Equipment();
        $file_http = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $file_http['value']);
        /**
         * 查询条件
         */
        $where = array();
        #设备名称
        $search_goods_name = trim(input('param.search_goods_name'));
        if ($search_goods_name != '') {
            $where['goods_name'] = array('like', '%' . $search_goods_name . '%');
        }
        #提交人
        $submission_name = trim(input('param.submission_name'));
        if ($submission_name != '') {
            $where['name'] = array('like', '%' . $submission_name . '%');
        }

        $b_id = intval(input('param.b_id'));
        if ($b_id > 0) {
            $where['b_id'] = $b_id;
        }
        //时间
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $where['ne.created_at'] = array('between', array($query_start_time, $query_end_time));
        }
        $addbricks_model = model('addbricks');
        // $where['sort'] = 0;
        $where['equipment_del'] = 0;
        $where['equipment_status'] = 0;
        $where['is_store'] = 1;
        //判断是那种类型
        $bricks_list = $equipmentModel->getEquipmentList($where, 10);

        // var_dump($bricks_list);exit;
        $this->assign('bricks_list', $bricks_list);
        $this->assign('show_page', $equipmentModel->page_info->render());

        $this->assign('search_goods_name', $search_goods_name);
        $this->assign('submission_name', $submission_name);
        $this->assign('b_id', $b_id);

        // $storage_array = $goods_model->calculateStorage($goods_list);
        // $this->assign('storage_array', $storage_array);

        // 品牌
        $brand_list = model('brand')->getBrandPassedList(array());
        $this->assign('search', $where);

        $this->assign('brand_list', $brand_list);

        $this->assign('enterprise_status', array('0' => '待审核', '1' => '审核通过', '2' => '审核失败'));

        $this->assign('ownShopIds', array_fill_keys(model('store')->getOwnShopIds(), true));

        $type = input('param.type');
        if (!in_array($type, array('lockup', 'waitverify', 'allgoods'))) {
            $type = 'allgoods';
        }
        $this->assign('is_examine', true);
        $this->assign('type', $type);
        $this->setAdminCurItem('two_goods_wait');
        return $this->fetch('bicks_list');
    }

    //添加
    public function add(Request $request)
    {
        $model = new \app\common\model\Question();
        // $this->setAdminCurItem('add');
        if (!request()->isPost()) { // 点击添加页面
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
            $this->assign('class_list', $parent_class_list);


            //分类
            $goodsclass_model = model('goodsclass');
            $type = [
                'class_id' => 0,
            ];
            $this->assign('type', $type);
            #获取顶级分类
            $where = array();
            $where['gc_parent_id'] = 0;
            $where['gc_show'] = 1;
            $field = '';
            $field = 'gc_id,gc_name';
            $top_goods_class = $goodsclass_model->getgoodsclassinfo($where, $field);
            if (empty($top_goods_class)) {
                $this->error('暂无顶级分类');
            }

            #获取品牌
            $field = '';
            //父类列表，只取到第二级
            $parent_list = $goodsclass_model->getTreeClassList(2);
            $gc_list = array();
            if (is_array($parent_list)) {
                foreach ($parent_list as $k => $v) {
                    $parent_list[$k]['gc_name'] = str_repeat("&nbsp;", $v['deep'] * 2) . $v['gc_name'];
                    if ($v['deep'] == 1)
                        $gc_list[$k] = $v;
                }
            }
            $this->assign('gc_list', $gc_list);
            $this->assign('top_goods_class', $top_goods_class);


            $brand_array = [
                'xianshi_state' => 1,
            ];
            $this->assign('brand_array', $brand_array);

            return $this->fetch('add');
        }
        //-----------------------------------------------
        $data = input('post.');

        $param = [
            'goods_name' => $data['goods_name'],
            'class_name' => $data['class_name'],
            'created_at' => date('Y-m-d H:i:s'),
            'status' => $data['status'],
            'is_store' => 0,
            'equipment_status' => 1,
            'member_id' => 0,
            'operator_id' => Session::get('admin_id'),
            'operator_name' => Session::get('admin_name'),
            'equipment_images' => $data['videos']
        ];

        //处理分类
        $class = db('goodsclass')->where(['gc_id' => $data['class_id']])->find();
        if (empty($class['gc_parent_id'])) {
            //没父值的话就是一级分类id
            $param['gc_one_id'] = $class['gc_id'];
            $param['gc_id'] = $class['gc_id'];
            $param['class_name'] = $class['gc_name'];
        } else {
            //有父值的话再往上找
            $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
            if (empty($class_one['gc_parent_id'])) {
                $param['gc_one_id'] = $class_one['gc_id'];
                $param['gc_two_id'] = $class['gc_id'];
                $param['gc_id'] = $class['gc_id'];
                $param['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
            } else {
                $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
                $param['gc_one_id'] = $class_two['gc_id'];
                $param['gc_two_id'] = $class_one['gc_id'];
                $param['gc_three_id'] = $class['gc_id'];
                $param['gc_id'] = $class['gc_id'];
                $param['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
            }
        }
        $result = db('new_equipment')->insertGetId($param);

        if ($result) {
            dsLayerOpenSuccess('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    /**
     * 编辑设备库
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function equipment_edit(Request $request)
    {
        $id = input('get.id', '', 'intval');
        $this->setAdminCurItem('equipment_edit');
        if (!$id) {
            return $this->error('参数错误');
        }
        $equipment_list = db('new_equipment')->where(['id' => $id])->find();

        if (!request()->isPost()) {
            $this->assign('equipment_list', $equipment_list);

            //分类
            $goodsclass_model = model('goodsclass');
            $type = [
                'class_id' => 0,
            ];
            $this->assign('type', $type);
            #获取顶级分类
            $where = array();
            $where['gc_parent_id'] = 0;
            $where['gc_show'] = 1;
            $field = '';
            $field = 'gc_id,gc_name';
            $top_goods_class = $goodsclass_model->getgoodsclassinfo($where, $field);
            if (empty($top_goods_class)) {
                $this->error('暂无顶级分类');
            }

            #获取品牌
            $field = '';
            //父类列表，只取到第二级
            $parent_list = $goodsclass_model->getTreeClassList(2);
            $gc_list = array();
            if (is_array($parent_list)) {
                foreach ($parent_list as $k => $v) {
                    $parent_list[$k]['gc_name'] = str_repeat("&nbsp;", $v['deep'] * 2) . $v['gc_name'];
                    if ($v['deep'] == 1)
                        $gc_list[$k] = $v;
                }
            }
            $this->assign('gc_list', $gc_list);
            $this->assign('top_goods_class', $top_goods_class);


            $brand_array = [
                'xianshi_state' => 1,
            ];
            $this->assign('brand_array', $brand_array);
            $config = db('config')->where('code', 'qiniu_http')->find();
            $this->assign('http_name', $config['value']);
            return $this->fetch('edit');
        }
        // ----------------------------------
        $data = input('post.');
        //环境配置
        $science_array = input('post.science/a'); #获取数组

        $param = [
            'goods_name' => $data['goods_name'],
            'class_name' => empty($data['class_name']) ? $equipment_list['class_name'] : $data['class_name'],
            'updated_at' => date('Y-m-d H:i:s'),
            'status' => $data['status'],
            'operator_id' => Session::get('admin_id'),
            'operator_name' => Session::get('admin_name'),
            'equipment_images' => empty($data['videos']) ? $equipment_list['equipment_images'] : $data['videos'],
        ];

        //处理分类
        if (empty($data['class_id'])) {
            $param['gc_one_id'] = $equipment_list['gc_one_id'];
            $param['gc_two_id'] = $equipment_list['gc_two_id'];
            $param['gc_three_id'] = $equipment_list['gc_three_id'];
            $param['gc_id'] = $equipment_list['gc_id'];
            $param['class_name'] = $equipment_list['class_name'];
        } else {
            $class = db('goodsclass')->where(['gc_id' => $data['class_id']])->find();
            if (empty($class['gc_parent_id'])) {
                //没父值的话就是一级分类id
                $param['gc_one_id'] = $class['gc_id'];
                $param['gc_id'] = $class['gc_id'];
                $param['class_name'] = $class['gc_name'];
            } else {
                //有父值的话再往上找
                $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
                if (empty($class_one['gc_parent_id'])) {
                    $param['gc_one_id'] = $class_one['gc_id'];
                    $param['gc_two_id'] = $class['gc_id'];
                    $param['gc_id'] = $class['gc_id'];
                    $param['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
                } else {
                    $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
                    $param['gc_one_id'] = $class_two['gc_id'];
                    $param['gc_two_id'] = $class_one['gc_id'];
                    $param['gc_three_id'] = $class['gc_id'];
                    $param['gc_id'] = $class['gc_id'];
                    $param['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
                }
            }
        }
        $result = db('new_equipment')->where(['id' => $id])->update($param);
        dsLayerOpenSuccess(lang('修改成功'));
    }


    //品牌管理
    public function brand_stration()
    {
        //设备库id
        $id = trim(input('param.id'));


        $equipmentModel = new \app\common\model\Equipment();

        $brand_name = input('get.brand_name', '');
        $question_name = input('get.question_name', '');

        $condition = [];
        $condition['equipment_id'] = $id;
        if ($brand_name) {
            $condition['brand_name'] = array('like', "%" . $brand_name . "%");
        }
        if ($question_name) {
            $condition['question_name'] = array('like', "%" . $question_name . "%");
        }

        $condition['equipment_brand_del'] = 0;
        $equipment_list = $equipmentModel->getNquipmentBrandList($condition, 10);

        $class = new Goodsclass();
        $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
        $this->assign('class_list', $parent_class_list);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件

        $this->assign('brand_name', $brand_name);
        $this->assign('question_name', $question_name);
        $this->assign('equipment_id', $id);
        $this->assign('equipment_list', $equipment_list);
        $this->assign('show_page', $equipmentModel->page_info->render());
        $this->assign('questionModel', $equipmentModel);

        $this->setAdminCurItem('brand_stration');
        return $this->fetch();
    }

    //品牌添加
    public function brand_add(Request $request)
    {
        $model = new \app\common\model\Question();
        $this->setAdminCurItem('brand_stration');
        $equipment_id = trim(input('param.id'));  #设备id
        $equipment_info = db('new_equipment')->where(['id' => $equipment_id])->find();
        if (!request()->isPost()) { // 点击添加页面
            //品牌
            $gc_id = $equipment_info['gc_one_id'] . ',' . $equipment_info['gc_two_id'] . ',' . $equipment_info['gc_three_id'];
            $where['gc_id'] = array('in', $gc_id);
            $brand_list = model('brand')->getBrandPassedList(array());
            $this->assign('brand_list_new', $brand_list);
            //获取问题
            $question = db('question')->where(['status' => 1])->select();
            $this->assign('question', $question);

            $brand_array = [
                'xianshi_state' => 1,
            ];
            $this->assign('brand_array', $brand_array);

            //环境配置判断
            $science = input('science');
            if (empty($science)) {
                
            }
            //start 规格

            // 实例化商品分类模型
            $goodsclass_model = model('goodsclass');
            // 更新常用分类信息
            $goods_class = $goodsclass_model->getGoodsclassLineForTag($equipment_info['gc_id']);
            $this->assign('goods_class', $goods_class);

            // 获取类型相关数据
            $typeinfo = model('type')->getNewAttribute($goods_class['type_id'], 6, $equipment_info['gc_id']);
            list($spec_json, $spec_list, $attr_list, $brand_list) = $typeinfo;
            $this->assign('sign_i', count($spec_list));
            $this->assign('spec_list', $spec_list);
            $this->assign('attr_list', $attr_list);
            $this->assign('brand_list', $brand_list);

            // end

            return $this->fetch('brand_add');
        }
        //-----------------------------------------------
        $data = input('post.');
        // sp_name   #  array(2) { [17]=> string(6) "规格" [18]=> string(6) "型号" }
        // sp_val    #  [17]=> array(2) { [535]=> string(6) "白色" [537]=> string(6) "黑色" }
        //              [18]=> array(2) { [536]=> string(3) "1.0" [538]=> string(3) "2.0" } }
        // ["spec"]=> array(4) { ["i_535536"]=> array(1) { ["sp_value"]=> array(2) { [535]=> string(6) "白色" [536]=> string(3) "1.0" } } ["i_535538"]=> array(1) { ["sp_value"]=> array(2) { [535]=> string(6) "白色" [538]=> string(3) "2.0" } } ["i_537536"]=> array(1) { ["sp_value"]=> array(2) { [537]=> string(6) "黑色" [536]=> string(3) "1.0" } } ["i_537538"]=> array(1) { ["sp_value"]=> array(2) { [537]=> string(6) "黑色" [538]=> string(3) "2.0" } } }


        //环境配置
        $science_array = input('post.science/a'); #获取数组
        $science = implode(',', $science_array);

        //获取option的所有id
        $option = input('post.option', 0);
        $option = trim($option, ',');
       
        $data['b_id'] = trim($data['b_id'],",");
        $b_ids = explode(",",$data['b_id']);
        
          
        $data['b_name'] = trim($data['b_name'],",");
        $b_names = explode(",",$data['b_name']);
        

        //获取对应的题库名称
        $question_info = db('question')->where(['id' => $data['question']])->find();

        $param = [
            'brand_name' => $data['b_name'][0],
            'brand_id' => $data['b_id'][0],
            'equipment_id' => $equipment_id,
            'question_id' => $question_info['id'],
            'question_name' => $question_info['title'],
            // 'specifications' => $data['specifications'],
            // 'type_model' => $data['type_model'],
            'installation_hours' => $data['installation_hours'],
            'dismantling_hours' => $data['dismantling_hours'],
            'brand_created_at' => date('Y-m-d H:i:s'),
            'brand_updated_at' => date('Y-m-d H:i:s'),
            'option' => $option,
            'science' => $science,
        ];
        $param['spec_name'] = is_array(input('post.spec/a')) ? serialize(input('post.sp_name/a')) : serialize(null);  #规格名  array(2) { [17]=> string(6) "规格" [18]=> string(6) "型号" }
        $param['spec_value'] = is_array(input('post.spec/a')) ? serialize(input('post.sp_val/a')) : serialize(null);

        $spec_array = input('post.spec/a'); #获取数组   规格型号数组

        if (!empty($spec_array)) {
            $new_array = array_filter($spec_array); #去空
            $spec_array_type = array();  #建立一个新数组

            foreach ($new_array as $value) {
                $spec_array_type[] = implode(',', $value['sp_value']);
            }

            $spec_array_type = serialize($spec_array_type); #序列化存起来
            $param['spec_value_type'] = $spec_array_type; #用这个
        }

        //判断是否已经添加过

    

        $is_brand = '';
 
        foreach($b_ids as $key => $b_id){

            $param['brand_name'] = $b_names[$key];
            $param['brand_id'] = $b_id;
            

            $is_add = db('new_equipment_brand')->where(['equipment_id' => $equipment_id,'brand_id'=>$param['brand_id']])->find();

            if($is_add){
                $is_brand .= $param['brand_name'];
               continue ;
            }

            $result = db('new_equipment_brand')->insertGetId($param);

            //更新部位表的父id
            QuestionOption::addEquipmentId($option, $result);
    
          
            //更新环境配置表的父id
            QuestionOption::addScienceId($data['science'], $result);
    
            //更新设备库主表信息
            $equipment_info = db('new_equipment')->where(['id' => $equipment_id])->find();
            if (empty($equipment_info['equipment_band_id'])) {
                //如果第一次没有添加品牌
                db('new_equipment')->where(['id' => $equipment_id])->update(['equipment_band_id' => $result]);
            } else {
                //拼接
                $new_brand_id = $equipment_info['equipment_band_id'] . ',' . $result;
                db('new_equipment')->where(['id' => $equipment_id])->update(['equipment_band_id' => $new_brand_id]);
            }
    
        }


        if (isset($result) && !empty($result)) {
            if($is_brand!==''){
                dsLayerOpenSuccess("添加成功,其中 $is_brand 已经添加");
            }
                dsLayerOpenSuccess("添加成功");
        } else {
            dsLayerOpenSuccess("添加失败，品牌已经添加过");
        }
    }

    /**
     * 品牌编辑
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function brand_edit(Request $request)
    {
        $id = input('get.id', '', 'intval');
        $this->setAdminCurItem('brand_stration');
        if (!$id) {
            return $this->error('参数错误');
        }
        $new_equipment_list = db('new_equipment_brand')->where(['equipment_brand_id' => $id])->find();
        $equipment_info = db('new_equipment')->where(['id' => $new_equipment_list['equipment_id']])->find();
        $option_list = db('equipment_option')->where(['equipment_id' => $id])->select();
        $science_list = db('equipment_science')->where(['equipment_id' => $id])->select();
        //$science_array = json_decode($equipment_list['science']);

        if (!request()->isPost()) {
            $this->assign('equipment_list', $new_equipment_list);
            $this->assign('option_list', $option_list);
            //$this->assign('science_array', $science_array);
            $this->assign('science_list', $science_list);

            //品牌
            $brand_list = model('brand')->getBrandPassedList(array());
            $this->assign('brand_list', $brand_list);

            //获取问题
            $question = db('question')->where(['status' => 1])->select();
            $this->assign('question', $question);

            //start 规格

            // 实例化商品分类模型
            $goodsclass_model = model('goodsclass');
            // 更新常用分类信息
            $goods_class = $goodsclass_model->getGoodsclassLineForTag($equipment_info['gc_id']);
            $this->assign('goods_class', $goods_class);

            // 获取类型相关数据
            $typeinfo = model('type')->getNewAttribute($goods_class['type_id'], 1000, $equipment_info['gc_id'], $new_equipment_list);
            list($spec_json, $spec_list, $attr_list, $brand_list) = $typeinfo;
            $this->assign('sign_i', count($spec_list));
            $this->assign('spec_list', $spec_list);
            $this->assign('attr_list', $attr_list);
            $this->assign('brand_list', $brand_list);


            $goodscommon_info1 = unserialize($new_equipment_list['spec_name']);
            $this->assign('spec_value_type1', $goodscommon_info1);

            // array(2) { [17]=> array(2) { ["sp_name"]=> string(6) "规格" ["value"]=> array(4) { [0]=> array(3) { ["spvalue_id"]=> int(668) ["spvalue_name"]=> string(2) "11" ["spvalue_color"]=> NULL } [1]=> array(3) { ["spvalue_id"]=> int(670) ["spvalue_name"]=> string(2) "44" ["spvalue_color"]=> NULL } [2]=> array(3) { ["spvalue_id"]=> int(672) ["spvalue_name"]=> string(6) "黑色" ["spvalue_color"]=> NULL } [3]=> array(3) { ["spvalue_id"]=> int(674) ["spvalue_name"]=> string(6) "白色" ["spvalue_color"]=> NULL } } } [18]=> array(2) { ["sp_name"]=> string(6) "型号" ["value"]=> array(4) { [0]=> array(3) { ["spvalue_id"]=> int(669) ["spvalue_name"]=> string(2) "22" ["spvalue_color"]=> NULL } [1]=> array(3) { ["spvalue_id"]=> int(671) ["spvalue_name"]=> string(2) "33" ["spvalue_color"]=> NULL } [2]=> array(3) { ["spvalue_id"]=> int(673) ["spvalue_name"]=> string(3) "1.0" ["spvalue_color"]=> NULL } [3]=> array(3) { ["spvalue_id"]=> int(675) ["spvalue_name"]=> string(3) "2.0" ["spvalue_color"]=> NULL } } } }

            // array(2) { [17]=> array(2) { [551]=> string(6) "白色" [553]=> string(6) "黑色" } [18]=> array(2) { [552]=> string(3) "1.0" [554]=> string(3) "2.0" } }
            $goodscommon_info2 = unserialize($new_equipment_list['spec_value']);

            $new = array();
            if (!empty($goodscommon_info2)) {
                foreach ($goodscommon_info2 as $key => $value) {
                    foreach ($value as $k => $v) {
                        $y = db('specvalue')->where(['spvalue_id' => $k])->find();
                        $new[$key][] = $y;
                    }
                }
            }

            $this->assign('spec_value_type2', $new);

            $goodscommon_info3 = unserialize($new_equipment_list['spec_value_type']);
            $this->assign('spec_value_type3', $goodscommon_info3);

            // end

            $brand_array = [
                'xianshi_state' => 1,
            ];
            $this->assign('brand_array', $brand_array);
            return $this->fetch('brand_edit');
        } else {
            // ----------------------------------
            $data = input('post.');

            //环境配置
            $science_array = input('post.science/a'); #获取数组
            $science = implode(',', $science_array);

            //将库里的取出来
            $science_info = json_decode($new_equipment_list['science'], true);

            //判断库里是否有值
            if (!empty($science_info)) {
                // 有值的话数组合并
                if (empty($science_array)) {
                    // 再判断修改过来的是否有值
                    $new_science_array = $science_info;
                } else {
                    $new_science_array = $science_info;
                    // $new_science_array = array_merge($science_array, $science_info);
                }
            } else {
                // 没值的话 直接更新最新的环境配置
                $new_science_array = $science_array;
            }

            //获取option的所有id
            $option = input('post.option', 0);
            $option = trim($option, ',');
            //获取对应的题库名称
            $question_info = db('question')->where(['id' => $data['question']])->find();
            $param = [
                'question_id' => $question_info['id'],
                'question_name' => $question_info['title'],
                // 'specifications' => $data['specifications'],
                // 'type_model' => $data['type_model'],
                'installation_hours' => $data['installation_hours'],
                'dismantling_hours' => $data['dismantling_hours'],
                'brand_updated_at' => date('Y-m-d H:i:s'),
                'option' => $option,
                'science' => $science
            ];
            $param['spec_name'] = is_array(input('post.spec/a')) ? serialize(input('post.sp_name/a')) : serialize(null);  #规格名  array(2) { [17]=> string(6) "规格" [18]=> string(6) "型号" }
            $param['spec_value'] = is_array(input('post.spec/a')) ? serialize(input('post.sp_val/a')) : serialize(null);

            $spec_array = input('post.spec/a'); #获取数组   规格型号数组
            $spec_array_type = array();  #建立一个新数组
            if (!empty($spec_array)) {
                $new_array = array_filter($spec_array); #去空
                foreach ($new_array as $value) {
                    $spec_array_type[] = implode(',', $value['sp_value']);
                }
            }
            $spec_array_type = serialize($spec_array_type); #序列化存起来

            $param['spec_value_type'] = $spec_array_type; #用这个

            $result = db('new_equipment_brand')->where(['equipment_brand_id' => $id])->update($param);

            //更新部位表的父id
            QuestionOption::addEquipmentId($option, $id);

            //更新环境配置表的父id
            QuestionOption::addScienceId($data['science'], $id);

            // 接收选项下的原因
            $option_answer = $request->post('option_answer/a');
            $option_answer_del = $request->post('option_answer_del/a');
            if (empty($option_answer)) $option_answer = [];
            if (empty($option_answer_del)) $option_answer_del = [];

            QuestionOption::addAnswer($option_answer);
            foreach ($option_answer as $key => $val) {
                \app\common\model\Answer::addOptionId($val, $key);
            }
            foreach ($option_answer_del as $key => $val) {
                \app\common\model\Answer::addOptionId($val, 0, 2);
            }
            dsLayerOpenSuccess(lang('修改成功'));

        }

    }


    #审核页
    public function goods_verify()
    {

        $id = input('param.id');
        $bricks_info = db('new_equipment')->alias('ne')
            ->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
            ->where(['id' => $id])->find();
        $this->assign('joinin_detail', $bricks_info);
        $img = trim($bricks_info['equipment_images_array'], '"[]"');
        $new_img = str_replace('"', '', $img);
        $this->assign('equipment_images', explode(",", $new_img));

        $member_name = db('member')->where(['member_id' => $bricks_info['member_id']])->find();
        $this->assign('member_name', $member_name);

        $this->assign('bricks_id', $id);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        $this->assign('is_verify', true);
        return $this->fetch('goods_verify');
    }

    /**
     * 审核
     */
    public function bricks_verify()
    {
        $id = input('param.id');
        $status = input('post.verify_type');
        $reason = input('post.joinin_message');

        $enterprise_info = db('new_equipment')->where(['id' => $id])->find();
        if ($status == 'pass') {
            db('new_equipment')->where(['id' => $id])->update(['equipment_status' => 1, 'equipment_reason' => $reason, 'status' => 1]);

            $service_info = db('fuwu_personal')->where('id', $enterprise_info['member_id'])->find();

            $service_tianzhuan_money = db('config')->where('code', 'service_tianzhuan_money')->find();
            $total_money = $service_info['money'] + $service_tianzhuan_money['value'];
            $update_service_data = [
                'money' => $total_money,
            ];
            db('fuwu_personal')->where('id', $enterprise_info['member_id'])->data($update_service_data)->update();

            $insert_money_log_data = [
                'member_id' => $service_info['id'],
                'type' => 1,
                'name' => $service_info['name'],
                'money' => $service_tianzhuan_money['value'],
                'surplus_money' => $total_money,
                'money_type' => 2,
                'addtime' => time(),
                'desc' => '服务人员添砖通过',
            ];
            db('money_log')->data($insert_money_log_data)->insert();

        } else {
            db('new_equipment')->where(['id' => $id])->update(['equipment_status' => 2, 'equipment_reason' => $reason, 'status' => 1]);
        }
        dsLayerOpenSuccess('审核成功');
    }


    //详情
    public function goods_content()
    {
        $id = input('param.id');
        $bricks_info = db('new_equipment')->alias('ne')
            ->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')->where(['id' => $id])->find();
        $this->assign('joinin_detail', $bricks_info);
        $img = trim($bricks_info['equipment_images_array'], '"[]"');
        $new_img = str_replace('"', '', $img);
        $this->assign('equipment_images', explode(",", $new_img));

        $member_name = db('member')->where(['member_id' => $bricks_info['member_id']])->find();
        $this->assign('member_name', $member_name);

        $this->assign('id', $id);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        $this->assign('is_verify', false);
        $this->assign('enterprise_status', array('0' => '待审核', '1' => '审核通过', '2' => '审核失败'));
        return $this->fetch('goods_content');
    }


    //增加部位
    public function addOption()
    {
        $content = input('post.option', '');
        $an_content = input('post.an_option', '');
        $wei_content = input('post.wei_option', '');
        $parent_id = input('get.parent_id', '0');
        $lev = input('post.lev', '0'); // 级别
        if (empty($content)) return json_encode(['code' => 0, 'message' => '参数不能为空']);
        //        if (QuestionOption::uniqueOptionsByContent($content)) return json(['code' => 0, 'message' => '该现象已存在']);
        // 判断是否存在删除的里边了
        $del = input('post.deloption', '');
        if (is_string($del)) {
            $del = explode(',', trim($del, ','));
        }
        $data = [
            'content' => $content,
            'maintenance_hours' => $an_content,
            'repair_hours' => $wei_content,
            'parent_id' => $parent_id,
            'created_at' => time(),
            'lev' => $lev
        ];
        $result = db('equipment_option')->insertGetId($data);

        if (!$result) {
            return json(['code' => 0, 'message' => '添加失败']);
        }
        return json(['code' => 10000, 'message' => '添加成功', 'data' => ['id' => $result, 'lev' => $lev]]);
    }

    //增加环境配置
    public function addScience()
    {
        $data = input('post.');
        

        if (empty($data)) return json_encode(['code' => 0, 'message' => '参数不能为空']);


        $data = [
            'science' => $data['science'],
            'lev' => $data['lev'],
            'create_time' => time(),
            'sort' => 0,
        ];
        $result = db('equipment_science')->insertGetId($data);

        if (!$result) {
            return json(['code' => 0, 'message' => '添加失败']);
        }
        return json(['code' => 10000, 'message' => '添加成功', 'data' => ['id' => $result, 'lev' => $data['lev']]]);
    }


    /**
     * 删除设备库
     */
    public function equipment_del()
    {
        $id = input('param.id');
        // db('equipment')->where(['id'=>$id])->delete();
        db('new_equipment')->where(['id' => $id])->update(['equipment_del' => 1]);
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }

    /**
     * 删除品牌
     */
    public function equipment_brand_del()
    {
        $id = input('param.id');
        // db('equipment')->where(['id'=>$id])->delete();
        db('new_equipment_brand')->where(['equipment_brand_id' => $id])->update(['equipment_brand_del' => 1]);
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }


    /**
     * 删除环境配置
     */
    public function parts_del()
    {
        $data = input('param.');
        $del_parts_id = $data['del_parts_id'];

        // var_dump($science_value);
        // var_dump($data['equipment_id']);exit;


        $info = db('equipment')->where(['id' => $data['equipment_id']])->find();
        $science_info = db('equipment_science')->where(['id' => $del_parts_id])->find();

        $science = json_decode($info['science'], true);

        foreach ($science as $key => $value) {
            if ($value == $del_parts_id) {
                unset($science[$key]);
            }
        }
        $science = array_merge($science);
        db('equipment')->where(['id' => $data['equipment_id']])->update(['science' => json_encode($science)]);
        db('equipment_science')->where(['equipment_id' => $data['equipment_id'], 'id' => $del_parts_id])->delete();
        return json(['code' => 100, 'message' => '删除成功', 'data' => []]);
    }

    /**
     * 删除部位
     */
    public function options_del()
    {
        $data = input('param.');
        // var_dump($science_value);
        // var_dump($data['equipment_id']);exit;
        $info = db('equipment_option')->where(['id' => $data['option_id']])->delete();
        return json(['code' => 100, 'message' => '删除成功', 'data' => []]);
    }

    /*
     * 上下架
     */

    public function equipment_status()
    {
        $id = trim(input('param.id'));
        $status = trim(input('param.status'));
        if (empty($id)) {
            ds_json_encode(10001, '参数错误');
        }
        $data = array();
        if ($status == 1) {
            $data['status'] = 2;
        } else {
            $data['status'] = 1;
        }
        $rs = db('new_equipment')->where('id', $id)->data($data)->update();
        if ($rs) {
            ds_json_encode(10000, '操作成功');
        } else {
            ds_json_encode(10001, '操作失败');
        }
    }

    /**
     * AJAX获取商品分类
     */
    public function ajax_class()
    {
        $id = intval(input('param.id'));
        $deep = intval(input('param.deep'));
        if ($id <= 0 || $deep <= 0 || $deep >= 4) {
            echo 'false';
            exit();
        }
        $deep += 1;
        $goodsclass_model = model('goodsclass');

        // 验证分类是否存在
        $gc_info = $goodsclass_model->getGoodsclassInfoByIds($id);
        if (empty($gc_info)) {
            echo 'false';
            exit();
        }

        // 读取商品分类
        if ($deep != 4) {
            $gc_list = $goodsclass_model->getGoodsclass($this->_store_id, $id, $deep);
        }
        // 分类不为空输出分类信息
        if (!empty($gc_list)) {
            $data = array('type' => 'class', 'data' => $gc_list, 'deep' => $deep);
        } else {
            // 查询类型
            $type_model = model('type');
            $spec_list = $type_model->getSpecByType(array('type_id' => $gc_info['type_id']), 't.type_id, s.*');

            $data = array('type' => 'spec', 'data' => $spec_list, 'gcid' => $id, 'aa' => $gc_info, 'gcid' => $id, 'deep' => $deep);
        }

        echo json_encode($data);
        exit();
    }


    /**
     * AJAx 获取分类
     */
    public function ajax_get_goods_class()
    {
        if (request()->isAjax()) {
            $goodsclass_model = model('goodsclass');
            $gc_id = trim(input('gc_id'));
            #获取手机顶级分类
            $where = array();
            $where['gc_parent_id'] = $gc_id;
            $where['gc_show'] = 1;
            $field = '';
            $field = 'gc_id,gc_name';
            $goods_class = $goodsclass_model->getgoodsclassinfo($where, $field);
            return $goods_class;
        } else {
            $this->error('访问错误');
        }
    }

    /**
     * AJAx 获取地区
     */
    public function ajax_get_area_class()
    {
        if (request()->isAjax()) {
            $area_model = model('area');
            $area_id = trim(input('area_id'));
            #获取手机顶级分类
            $where = array();
            $where['area_parent_id'] = $area_id;
            $field = '';
            $field = 'area_id,area_name';
            $area_class = $area_model->getarea_list($where, $field);
            return $area_class;
        } else {
            $this->error('访问错误');
        }
    }

    /**
     * AJAX添加商品规格值
     */
    public function ajax_add_spec()
    {
        $name = trim(input('get.name'));
        $gc_id = intval(input('get.gc_id'));
        $sp_id = intval(input('get.sp_id'));
        if ($name == '' || $gc_id <= 0 || $sp_id <= 0) {
            echo json_encode(array('done' => false));
            die();
        }
        $insert = array(
            'spvalue_name' => $name, 'sp_id' => $sp_id, 'gc_id' => $gc_id, 'store_id' => 6,
            'spvalue_color' => null, 'spvalue_sort' => 0,
        );
        $value_id = model('spec')->addSpecvalue($insert);
        if ($value_id) {
            echo json_encode(array('done' => true, 'value_id' => $value_id));
            die();
        } else {
            echo json_encode(array('done' => false));
            die();
        }
    }

    /*
      ajax 上传图片

     */
    public function ajax_upload()
    {
        $file_type = array('0' => 'image/jpeg', '1' => 'image/jpg', '2' => 'image/png');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $file_name = input('post.name');
            $upload_info = upload_qiniu('file');
            return $upload_info;
        } else {
            return $data['msg'] = 0;
        }
    }

    protected function getAdminItemList()
    {

        $menu_array = array(
            array(
                'name' => 'index',
                'text' => lang('ds_manage'),
                'url' => url('Nquipment/index')
            ),
            array(
                'name' => 'two_goods_no',
                'text' => '添砖记录',
                'url' => url('Nquipment/bicks_list')
            ),
            array(
                'name' => 'two_goods_wait',
                'text' => '待审核',
                'url' => url('Nquipment/two_goods_wait')
            ),
            array(
                'name' => 'add',
                'text' => lang('ds_new'),
                'url' => "javascript:dsLayerOpen('" . url('Nquipment/add') . "','" . '新增' . "')",
            ),
        );
        if (request()->action() == 'equipment_edit') {
            $menu_array[] = array(
                'name' => 'equipment_edit',
                'text' => lang('ds_edit'),
                'url' => url("Nquipment/equipment_edit"),
            );
            unset($menu_array[1]);
        }
        if (request()->action() == 'brand_stration') {
            $menu_array[] = array(
                'name' => 'brand_stration',
                'text' => '品牌管理',
                'url' => url("Nquipment/brand_stration", ['id' => input('param.id')]),
            );
        }
        return $menu_array;
    }
}
